import { createRouter, createWebHistory } from "vue-router";

// 路由懒加载优化
const routes = [
  {
    path: "/",
    name: "home",
    component: () => import(/* webpackChunkName: "home" */ "../views/index.vue"),
    meta: {
      title: "基层社区监测防控平台",
      keepAlive: true,
      preload: true
    }
  },
  // 错误页面
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import(/* webpackChunkName: "error" */ "../views/error/404.vue"),
    meta: {
      title: "页面未找到",
      keepAlive: false
    }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 滚动行为优化
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  }
});

// 路由守卫优化
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  
  // 路由权限检查
  if (to.name !== 'home' && to.name !== 'NotFound') {
    next('/');
  } else {
    next();
  }
});

// 路由错误处理
router.onError((error) => {
  console.error('路由错误:', error);
  // 可以跳转到错误页面
  router.push('/');
});

export default router;
